package mspbots.teams.data.core.users;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.teams.common.ResultMsg;
import mspbots.teams.data.core.BaseReceiver;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * @author Jay Yang
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class UsersReceiver extends BaseReceiver {

    private final UsersRepository usersRepository;

    @RabbitListener(queues = "data-teams.user.sync")
    public void processCompanies(ResultMsg resultMsg) {
        User data = User.builder()
                .otherId(resultMsg.getId())
                .tenantId(resultMsg.getTenantId())
                .syncTime(resultMsg.getSyncDate())
                .extend(resultMsg.getEntity())
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();

        this.usersRepository.findByOtherIdAndTenantId(data.getOtherId(), data.getTenantId())
                .switchIfEmpty(this.usersRepository.save(data))
                .filter(old->old.getUpdateTime().isBefore(data.getUpdateTime()))
                .map(old -> {
                    data.setId(old.getId());
                    return data;
                })
                .flatMap(this.usersRepository::save).block(Duration.ofSeconds(10));
    }
}
